/**
 * Copyright (c) 2010-2015 by skzr.org
 * All rights reserved.
 * @Author skzr.org(E-mail:skzr.org@gmail.com)
 * @date Feb 27, 2010 11:09:51 AM
 */
package org.skzr.framework.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @jdk 6.0
 * @author skzr.org(E-mail:skzr.org@gmail.com)
 * @version 1.0.1
 */
public class UtilIO {
	protected static final Logger logger = LoggerFactory.getLogger(UtilIO.class);
	private static int DEFAULT_SIZE = 2048;

	public static void close(OutputStream stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				logger.warn("忽略此异常", e);
			}
		}
	}

	public static void close(InputStream stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				logger.warn("忽略此异常", e);
			}
		}
	}

	private static int getBufferLen(long bufferLen) {
		return (bufferLen <= 0 || bufferLen > 2 * DEFAULT_SIZE || bufferLen > Integer.MAX_VALUE) ? DEFAULT_SIZE : (int) bufferLen;
	}

	public static void write(InputStream in, OutputStream out) throws IOException {
		write(in, out, 0);
	}
	public static void write(InputStream in, OutputStream out, long bufferLen) throws IOException {
		byte[] buffer = new byte[getBufferLen(bufferLen)];
		for (int len; (len = in.read(buffer)) != -1;) out.write(buffer, 0, len);
		out.flush();
	}

	public static ByteArrayOutputStream writeByteArrayOutputStream(InputStream in) throws IOException {
		return writeByteArrayOutputStream(in, 0);
	}
	
	public static ByteArrayOutputStream writeByteArrayOutputStream(InputStream in, long bufferLen) throws IOException {
		ByteArrayOutputStream out = null;
		try {
			int len = getBufferLen(bufferLen);
			out = new ByteArrayOutputStream(len);
			write(in, out, len);
		} finally {
			UtilIO.close(out);
		}
		return out;
	}

	public static ByteArrayInputStream convert(InputStream in) throws IOException {
		return convert(in, 0);
	}

	public static ByteArrayInputStream convert(InputStream in, long bufferLen) throws IOException {
		return in instanceof ByteArrayInputStream ? (ByteArrayInputStream) in : new ByteArrayInputStream(
				writeByteArrayOutputStream(in, bufferLen).toByteArray());
	}

	public static String readText(InputStream in) throws IOException {
		return writeByteArrayOutputStream(in, DEFAULT_SIZE).toString();
	}
	public static String readText(InputStream in, long size, String charset) throws IOException {
		return writeByteArrayOutputStream(in, size < 0 ? DEFAULT_SIZE : size).toString(charset);
	}
}